import {
  Component, OnInit, ViewEncapsulation, ViewChild, ElementRef,
  Renderer, OnDestroy
} from '@angular/core';
import {Subject} from "rxjs";

import {SeedInfiniteScroll} from '@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component';
import {ToolsService} from '@shared/service/tools/tools.service';
import {ImageServeService} from '@shared/service/image/image-serve.service';
import {GoodsService} from '../goods.service';
import {Router, Params, ActivatedRoute} from '@angular/router';
import {ColumnContentVO} from "../../../interface/column/column.models";
import {AppPlayTurn} from "@interface/index";


@Component({
  selector: 'goods-topic',
  templateUrl: './goods-topic.component.html',
  styleUrls: ['./goods-topic.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class GoodsTopicComponent implements OnInit, OnDestroy {

  public goodsModules: Array<ColumnContentVO> = [];
  public bannerObj: AppPlayTurn[];
  public recommendGoods: Array<any> = [];

  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  @ViewChild('card') card: ElementRef;
  @ViewChild('container') container: ElementRef;

  public params = {
    page: 1,
    rows: 10
  };
  public stateStore = {
    timer: null,
    haveRecommendGoods: false,
    mediaQuery: false, // 是否启用媒体查询
    intervalCount: 0,
    fullGoodsWidth: 0,
    halfGoodsWidth: 0,
    halfDefaultGraph: null,
  };
  public dataStore = {
    goodsType: [], // 商品类别
    banner: [],
    topicTitle: ''
  };
  public ngUnsubscribe: Subject<void> = new Subject<void>();

  constructor(private router: Router,
              private route: ActivatedRoute,
              public goodsService: GoodsService,
              public toolsService: ToolsService,
              public tools: ToolsService,
              public imgService: ImageServeService,
              private ele: ElementRef,
              private renderer: Renderer) {
    this.stateStore.halfDefaultGraph = imgService.getMiddleArticleImgHolder();
    this.route.params.subscribe((params: Params) => {
      const tipicId = params['topicId'];
      this.getSlider(tipicId);
      this.getGoodsModule(tipicId);
    });
  }

  /**
   * @description 获取轮播图
   * @author ouyqx-691
   * @date 2017-09-12
   */
  getSlider(topicId: string) {
    this.goodsService.getSlider(topicId).takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data) {
        this.dataStore.banner = res.data.banners;
        this.dataStore.topicTitle = res.data.topicName;
      }
    });
  };

  /**
   * @description 前往专题或商品详情
   * @author ouyqx-691
   * @date 2017/11/25
   * @param news 单个轮播对象
   */
  goToBannerTarget(slide) {
     // 外链且存在外链url
    if (slide.linkType === 2 && slide.detailUrl) {
       //  其它外链
      if (slide.detailUrl.indexOf('topicId') === -1) {
        window.open(slide.detailUrl);
      } else { // 专题
        const topicId = slide.detailUrl.split('topicId=')[1];
        this.router.navigate(['/goods/topic', topicId]);
      }
    } else { // 商品
      this.router.navigate(['/goods/detail', slide.resId ]);
    }
  }

  /**
   * @description go to goods list page
   * @param goodsTypeObj :goods type object
   */
  goToGoodsList(goodsTypeObj) {
    if (goodsTypeObj.targetUrl) {
      this.router.navigate(['/goods/nav']);
    } else {
      const goodsCategoryCode = goodsTypeObj.serviceUrl.split('goodsCategoryCode=')[1];
      if (goodsCategoryCode) {
        this.router.navigate(['/goods/list/', goodsCategoryCode], {
          queryParams: {
            title: encodeURI(goodsTypeObj.serviceName)
          }
        });
      }
    }
  }

  /**
   * @description 获取推荐商品布局信息
   * @author ouyqx-691
   * @date 2017-09-11
   */
  getGoodsModule(topicId: string) {
    this.tools.showLoading();
    this.goodsService.getGoodsModule(topicId).takeUntil(this.ngUnsubscribe).subscribe(res => {
      this.tools.hideLoading();
      if (res.result === '0') {
        this.goodsModules = res.data;
      }
    });
  };

  /**
   * @description 获取推荐商品
   * @author ouyqx-691
   * @date 2017-09-11
   */
  getRecommendGoods() {
    this.goodsService.getRecommendGoods(this.params).takeUntil(this.ngUnsubscribe).debounceTime(800).subscribe(res => {
      this.infiniteScroll.complete();
      if (res.result === '0' && res.data.list && res.data.list.length > 0) {
        const goods = res.data.list;
        this.params.page++;
        this.recommendGoods = this.recommendGoods.concat(goods);
        if (this.recommendGoods.length >= 200 || !res.data.hasNextPage) { // 限制只加载200条
          this.infiniteScroll.enable(false);
        }
      }
    });
  }

  /**
   * @description 处理是进入详情还是打开新窗口
   * @author ouyqx-691
   * @param goodsCode
   */
  handleDetail(goods) {
    if (goods.contentType === 1) {
      this.goToGoodsDetail(goods.realationKey);
    } else {
      const link: string = goods.linkUrl;
      if (goods.linkUrl) {
        window.open(link);
      }
    }
  }

  /**
   * @description 前往商品详情
   * @author ouyqx-691
   * @param goodsCode
   */
  goToGoodsDetail(goodsCode: string) {
    if (goodsCode) {
      this.router.navigate(['/goods/detail', goodsCode]);
    }
  }

  /**@description 图片适配
   * @author ouyqx-691
   */
  resizeImageHeight() {
    const screenWidth = window.screen.width;
    this.stateStore.fullGoodsWidth = screenWidth - 36;
    this.stateStore.halfGoodsWidth = (screenWidth - 48) / 2;

    this.resizeCardHeight();
  }

  /**@description 竖形卡片高度适配
   * @author ouyqx-691
   * @date 2017/09/25
   */
  resizeCardHeight() {
    let timer = this.stateStore.timer;
    timer = setInterval(() => {
      const allHalfContainer = this.ele.nativeElement.querySelectorAll('.custom-module .half .container');
      const halfGoodsContainer = this.ele.nativeElement.querySelector('.custom-module .half .goods-container');

      if (halfGoodsContainer) {
        const halfGoodsContainerHeight = halfGoodsContainer.clientHeight;
        for (let i = 0; i < allHalfContainer.length; i++) {
          allHalfContainer[i].style.height = halfGoodsContainerHeight + 'px';
        }
        clearInterval(timer);
      } else {
        this.stateStore.intervalCount++;
        if (this.stateStore.intervalCount >= 7) {  // 限定次数避免一直运行
          this.stateStore.mediaQuery = true;
          clearInterval(timer);
        }
      }
    }, 300);
  }


  ngOnInit() {

    this.getRecommendGoods();

    this.resizeImageHeight();

    this.renderer.listen(window, 'resize', () => {
      this.resizeImageHeight();
      this.resizeCardHeight();
    });
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  };
}
